#include "drogon/drogon.h"
#include "Util.h"

const String Util::DbName = "IceConverPre";
String Util::CachePath = "";
String Util::DataPath = "";
String Util::CachePath_ICE_COVER = "";
bool Util::KeepHistory = true;

// 24032808.000
StringVector Util::findM4File(String path)
{
	StringVector sv;
	auto files = FileUtil::findFiles(path);
	for (const auto& f : files)
	{
		if (f.size() == 12)
		{
			sv.push_back(f);
		}
	}

	return sv;
}

StringVector Util::findM4JsonFile(String path)
{
	StringVector sv;
	auto files = FileUtil::findFiles(path);
	for (const auto& f : files)
	{
		if (f.size() == 17 && StringUtil::endsWith(f, ".json"))
		{
			sv.push_back(f);
		}
	}

	return sv;
}

void Util::loadConfig()
{
	String yamlFileName = joinPath(Singleton(Environment).getAppPath(), "config", "OCPP_Project_IceCoverPre.yml");
	try {
		YAML::Node node = YAML::LoadFile(yamlFileName);
		DataPath = getYaml<String>(node, { "hxgis", "DataPath" });
		CachePath = getYaml<String>(node, { "hxgis", "CachePath" });
		KeepHistory = getYaml<bool>(node, { "hxgis", "KeepHistory" });
	}
	catch (const YAML::Exception& e) {
		OCPP_LOG_ERROR << e.msg << "\n";
		return;
	}

	if (!FileUtil::existFile(CachePath))
	{
		FileUtil::makeDirectory(CachePath);
	}

	CachePath_ICE_COVER = joinPath(CachePath, "ICE_COVER");

	if (!FileUtil::existFile(CachePath_ICE_COVER))
	{
		FileUtil::makeDirectory(CachePath_ICE_COVER);
	}

	OCPP_LOG_INFO << "DataPath:" << DataPath << "\n";
	OCPP_LOG_INFO << "CachePath:" << CachePath << "\n";
	OCPP_LOG_INFO << "CachePath_ICE_COVER:" << CachePath_ICE_COVER << "\n";
	OCPP_LOG_INFO << "KeepHistory:" << KeepHistory << "\n";
}

void Util::initDB()
{
	String fileName = joinPath(CachePath, Util::DbName + ".db");
	drogon::app().createDbClient("sqlite3", "", 0, "", "", "", 1, fileName, Util::DbName);
	if (!FileUtil::existFile(fileName))
	{
		drogon::app().getLoop()->runAfter(0, []() {
			drogon::orm::DbClientPtr dbClient = drogon::app().getDbClient(Util::DbName);
			try {
				String sql1 = "CREATE TABLE IF NOT EXISTS file_info(\
				file_gid INTEGER PRIMARY KEY,\
				file_path TEXT,\
				file_md5 TEXT)";
				String sql2 = "CREATE TABLE IF NOT EXISTS file_data(\
				file_md5 TEXT PRIMARY KEY,\
				file_size INTEGER,\
				file_data BLOB)";
				dbClient->execSqlSync(sql1);
				dbClient->execSqlSync(sql2);
				dbClient->execSqlSync("CREATE UNIQUE INDEX file_path_index ON file_info(file_path);");
				dbClient->execSqlSync("CREATE UNIQUE INDEX file_md5_index ON file_data(file_md5);");
			}
			catch (drogon::orm::DrogonDbException& ex) {
				LOG_ERROR << ex.base().what() << "\n";
			}
			catch (...) {
				LOG_ERROR << "unknow error.\n";
				return;
			}
			});
	}
}